package cn.net.isir.service2;

import com.alibaba.fastjson.JSON;
import com.alipay.api.response.AlipayOpenAgentFacetofaceSignResponse;
import com.alipay.api.response.AlipayOpenAgentOrderQueryResponse;
import cn.net.isir.common.ResultObject;
import cn.net.isir.common.pay.alipay.AlipayAgentAPI;
import cn.net.isir.dao.*;
import cn.net.isir.entity.*;
import cn.net.isir.utils.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author liuxubo
 * @filename AlipayOpenAgentFacetofaceSignService.java
 * @package cn.net.isir.service2
 * @email lxb@isir.net.cn
 * @date 2018/12/03
 * @comment 签约当面付业务服务
 * @since 1.8
 */
@Service
@Transactional
public class AlipayOpenAgentFacetofaceSignService {
    //声明日志对象
    private static Logger logger = Logger.getLogger(AlipayOpenAgentFacetofaceSignService.class);
    @Resource
    private ShopDao shopDao;
    @Resource
    private AlipayAuthDao alipayAuthDao;
    @Resource
    private BusinessInfoDao businessInfoDao;
    @Resource
    private AlipayAgentDao alipayAgentDao;
    @Resource
    private AlipayAgentService alipayAgentService;
    @Resource
    private FileUploadLogDao fileUploadLogDao;
    @Resource
    private PaymentDao paymentDao;


    /**
     * 提交当面付资料（自动开启、提交事务）
     *
     * @param businessInfo
     * @return 结果
     */
    public ResultObject submitOpenAgentFacetofaceSignInfo(BusinessInfo businessInfo) {
        Payment payment = paymentDao.selectByPrimaryKey(businessInfo.getPaymentId());
        logger.info("重新提交获取到的payment资料信息");
        logger.info(payment.toString());
        /**
         * 查询授权信息（为了获取userid和token）
         */
        AlipayAuth auth = alipayAuthDao.selectByPrimaryKey(payment.getBindingAuthInfoId());

        //开启事务
        String batch_no = alipayAgentService.alipayOpenAgentCreate(
                auth.getApp_auth_token(),
                auth.getUser_id(),
                businessInfo.getContact(),
                businessInfo.getContactTel(),
                businessInfo.getContactEmail());
        //经营类目
        String mccCode = "C_C05_5812";//餐厅、订餐服务
        mccCode = businessInfo.getMccCode();

        logger.info("参数输出");
        logger.info(auth.getApp_auth_token());
        logger.info(batch_no);
        logger.info(mccCode);
        logger.info(fileUploadLogDao.selectByPrimaryKey(businessInfo.getSpecialLicensePic()).toString());
        logger.info(businessInfo.getLicenseNo());
        logger.info(fileUploadLogDao.selectByPrimaryKey(businessInfo.getLicensePic()).toString());
        logger.info(fileUploadLogDao.selectByPrimaryKey(businessInfo.getLicenseAuthPic()).toString());
        logger.info(fileUploadLogDao.selectByPrimaryKey(businessInfo.getShopSignBoardPic()).toString());


        // 签约
        AlipayOpenAgentFacetofaceSignResponse response =
                AlipayAgentAPI.alipayOpenAgentFacetofaceSign(
                        auth.getApp_auth_token(),
                        batch_no,
                        mccCode,
                        fileUploadLogDao.selectByPrimaryKey(businessInfo.getSpecialLicensePic()).getNewPath(),//businessInfo.getSpecialLicensePic(),
                        businessInfo.getLicenseNo(),
                        fileUploadLogDao.selectByPrimaryKey(businessInfo.getLicensePic()).getNewPath(),
                        fileUploadLogDao.selectByPrimaryKey(businessInfo.getLicenseAuthPic()).getNewPath(),
                        fileUploadLogDao.selectByPrimaryKey(businessInfo.getShopSignBoardPic()).getNewPath());

        if (response == null || !response.isSuccess()) {
            //取消事务
            alipayAgentService.alipayOpenAgentCancel(batch_no);
            //返回
            return new ResultObject(500, "fail", null);
        }

        //提交事务
        boolean submitStatus = alipayAgentService.alipayOpenAgentConfirm(batch_no);
        if (!submitStatus) {
            return new ResultObject(500, "fail", null);
        }

        //成功提交之后，保存事务
        AlipayAgent alipayAgent = new AlipayAgent();
//        alipayAgent.setShopId(shopId);
        alipayAgent.setAccount(auth.getUser_id());
        alipayAgent.setContact_name(businessInfo.getContact());
        alipayAgent.setContact_mobile(businessInfo.getContactTel());
        alipayAgent.setContact_email(businessInfo.getContactEmail());
        alipayAgent.setOrder_ticket(null);
        alipayAgent.setBatch_no(batch_no);
        alipayAgent.setBatch_status("submit");
        alipayAgent.setAgentType("sign");
        alipayAgentDao.insert(alipayAgent);

        //更新支付手段状态
        payment.setAgentInfoId(alipayAgent.getId());
        payment.setSignStatus("1");
        paymentDao.update(payment);
        return new ResultObject(200, "success", null);
    }

    /**
     * 提交当面付资料（自动开启、提交事务）
     *
     * @return 结果
     */
    public ResultObject submitOpenAgentFacetofaceSignInfo2(String shopId) {
        //获取店铺信息
        Shop shop = shopDao.selectByPrimaryKey(shopId);
        //获取授权信息
        AlipayAuth auth = new AlipayAuth();
        auth.setShopId(shopId);
        auth = alipayAuthDao.selectOne(auth);
        //获取运营信息
        BusinessInfo businessInfo = businessInfoDao.selectByPrimaryKey(shop.getAlipayBusinessInfo());
        logger.info("submitOpenAgentFacetofaceSignInfo-businessInfo");
        logger.info(businessInfo.toString());
        //开启事务
        String batch_no = alipayAgentService.alipayOpenAgentCreate(
                auth.getApp_auth_token(),
                auth.getUser_id(),
                businessInfo.getContact(),
                businessInfo.getContactTel(),
                businessInfo.getContactEmail());
        //经营类目
        String mccCode = "C_C05_5812";//餐厅、订餐服务
        mccCode = businessInfo.getMccCode();

        // 签约
        AlipayOpenAgentFacetofaceSignResponse response =
                AlipayAgentAPI.alipayOpenAgentFacetofaceSign(
                        auth.getApp_auth_token(),
                        batch_no,
                        mccCode,
                        businessInfo.getSpecialLicensePic(),//businessInfo.getSpecialLicensePic(),
                        businessInfo.getLicenseNo(),
                        fileUploadLogDao.selectByPrimaryKey(businessInfo.getLicensePic()).getNewPath(),
                        fileUploadLogDao.selectByPrimaryKey(businessInfo.getLicenseAuthPic()).getNewPath(),
                        fileUploadLogDao.selectByPrimaryKey(businessInfo.getShopSignBoardPic()).getNewPath());

        if (response == null || !response.isSuccess()) {
            //取消事务
            alipayAgentService.alipayOpenAgentCancel(batch_no);
            //返回
            return new ResultObject(500, "fail", null);
        }

        //提交事务
        boolean submitStatus = alipayAgentService.alipayOpenAgentConfirm(batch_no);
        if (!submitStatus) {
            return new ResultObject(500, "fail", null);
        }

        //成功提交之后，保存事务
        AlipayAgent alipayAgent = new AlipayAgent();
        alipayAgent.setShopId(shopId);
        alipayAgent.setAccount(auth.getUser_id());
        alipayAgent.setContact_name(businessInfo.getContact());
        alipayAgent.setContact_mobile(businessInfo.getContactTel());
        alipayAgent.setContact_email(businessInfo.getContactEmail());
        alipayAgent.setOrder_ticket(null);
        alipayAgent.setBatch_no(batch_no);
        alipayAgent.setBatch_status("submit");
        alipayAgent.setAgentType("sign");
        alipayAgentDao.insert(alipayAgent);
//        更改店铺授权状态
//        shop.setAlipaySignStatus("2");//2表示已提交审核中
//        shopDao.update(shop);
        //返回
        return new ResultObject(200, "success", alipayAgent.getId());
    }

    /**
     * 保存当面付资料(如果已经授权，会自动提交资料)
     *
     * @param businessInfo 资料
     * @return 保存结果
     */
//    public ResultObject saveOpenAgentFacetofaceSignInfo(Shop shop, BusinessInfo businessInfo) {
////        String shopid = businessInfo.getShopId();
////        Shop shop = shopDao.selectByPrimaryKey(shopid);
//        //如果已经授权，直接提交
//        if ("1".equals(shop.getAlipayAuthStatus())) {
//            ResultObject ro = submitOpenAgentFacetofaceSignInfo(shop.getId());
//            if (ro.getResult() != 200) {
//                return ro;
//            }
//        }
//        return new ResultObject(200, "success", businessInfo.getId());
//    }

    /**
     * 根据店铺id，更新签约状态
     *
     * @param paymentIdList 店铺列表
     * @return 结果
     */
    public boolean updateOpenAgentFacetofaceSignStatus(List<String> paymentIdList) {
        if (paymentIdList == null || paymentIdList.size() == 0) {
            return false;
        }
        logger.info("执行，签约需要查询的支付方式id列表");
        paymentIdList.forEach(item -> logger.info(item));
        // 查询事务编号
        for (String paymentId : paymentIdList) {
            logger.info("当前正在执行查询的支付方式ID[" + paymentId + "]");
            Payment payment = paymentDao.selectByPrimaryKey(paymentId);
            if (payment == null || "0".equals(payment.getSignStatus()) || "3".equals(payment.getSignStatus())) {
                continue;
            }
            if (StringUtils.isBlank(payment.getAgentInfoId())) {
                continue;
            }

            //查询事务信息
            AlipayAgent agent = alipayAgentDao.selectByPrimaryKey(payment.getAgentInfoId());
            // 请求平台接口
            AlipayOpenAgentOrderQueryResponse response =
                    alipayAgentService.alipayOpenAgentOrderQuery(agent.getBatch_no());
            logger.info("支付手段" + paymentId + "查询结果：" + JSON.toJSONString(response));
            logger.info(response);
            if (response == null || !response.isSuccess()) {
                continue;
            }
            // 如果有通过的。更新状态
            String orderStatus = response.getOrderStatus();
            //MERCHANT_INFO_HOLD=暂存，提交事务出现业务校验异常时，会暂存申请单信息，可以调用业务接口修正参数，并重新提交
            if (orderStatus.equals("MERCHANT_INFO_HOLD")) {
                payment.setSignStatus("4");
            }
            //MERCHANT_AUDITING=审核中，申请信息正在人工审核中
            if (orderStatus.equals("MERCHANT_AUDITING")) {
//                shop.setAlipaySignStatus("1");
                continue;
            }
            //MERCHANT_CONFIRM=待商户确认，申请信息审核通过，等待联系人确认签约或授权
            if (orderStatus.equals("MERCHANT_CONFIRM")) {
                //如果已经修改状态，则无需重新修改
                if ("2".equals(payment.getSignStatus())) {
                    continue;
                }
                payment.setSignStatus("2");
                agent.setSign_confirm_url(response.getConfirmUrl());
                alipayAgentDao.update(agent);
            }
            //MERCHANT_CONFIRM_SUCCESS=商户确认成功，商户同意签约或授权
            if (orderStatus.equals("MERCHANT_CONFIRM_SUCCESS")) {
                payment.setSignStatus("3");
                // 更新签约信息状态
                BusinessInfo businessInfo =
                        businessInfoDao.selectByPrimaryKey(payment.getBindingSignInfoId());
                businessInfo.setStatus("signed");
                businessInfoDao.update(businessInfo);
            }
            //MERCHANT_CONFIRM_TIME_OUT=商户超时未确认，如果商户受到确认信息15天内未确认，则需要重新提交申请信息
            if (orderStatus.equals("MERCHANT_CONFIRM_TIME_OUT")) {
                payment.setSignStatus("5");
            }
            //MERCHANT_APPLY_ORDER_CANCELED=审核失败或商户拒绝，申请信息审核被驳回，或者商户选择拒绝签约或授权
            if (orderStatus.equals("MERCHANT_APPLY_ORDER_CANCELED")) {
                payment.setSignStatus("6");
            }
            //更新店铺信息
            paymentDao.update(payment);
            logger.info("ID是[" + paymentId + "]的支付方式查询完成，状态是[" + payment.getSignStatus() + "]");
        }
        return true;
    }
}
